import { saveConsigneeConsignerApi } from "./api";
import { useTzRouter } from "@/vhooks/useTzRouter";
import { isEmpty } from "@/utils/validate";
import { getDicMap, regCommonChar } from "@/utils";

const dicMap = getDicMap();

// 匹配收发货人国家名称
const matchCountryName = (code) => {
  return dicMap.stateCodeList.filter((item) => item.code === code)[0]?.nameCn;
};

/**
 * 收发货人保存
 * @param {String} type consignor 发货人  consignee 收货人
 * @param {Number} both 1 保存全部
 */
export const saveReceiveMan = ({ type, state }) => {
  console.log("收发货人保存", type);
  const fetchParams = {
    // 发货人
    consignor() {
      if (consignorInvalida(state)) {
        $TzNotify.danger(consignorInvalida(state));
        return false;
      }
      const {
        consignorName: name,
        consignorAddr: address,
        consignorCountryCode: countryCode,
      } = state.receiveForm;
      return {
        name,
        address,
        countryCode,
        countryName: matchCountryName(countryCode),
      };
    },
    // 收货人
    consignee() {
      if (consigneeInvalida(state)) {
        $TzNotify.danger(consigneeInvalida(state));
        return false;
      }
      const {
        consigneeName: name,
        consigneeAddr: address,
        consigneeCountryCode: countryCode,
      } = state.receiveForm;
      return {
        name,
        address,
        countryCode,
        countryName: matchCountryName(countryCode),
      };
    },
  };
  let params = null;
  if (type === "both") {
    params = { ...fetchParams.consignor(), ...fetchParams.consignee() };
  } else {
    params = fetchParams[type]();
  }
  params &&
    saveConsigneeConsignerApi(params)
      .then(() => {
        type !== "both" && $TzNotify.success("保存成功");
      })
      .catch((err) => {
        type !== "both" && $TzNotify.danger(err.data.msg || "保存失败");
      });
};

// 校验发货人 有返回错误信息表示校验不通过；返回 false 表示校验通过
export const consignorInvalida = (state) => {
  let errorMsg = "";
  const {
    consignorName,
    consignorAddr,
    consignorCountryCode,
  } = state.receiveForm;
  if (isEmpty(consignorName)) {
    errorMsg = "请输入发货人名称";
  } else if (isEmpty(consignorAddr)) {
    errorMsg = "请输入发货人地址";
  } else if (isEmpty(consignorCountryCode)) {
    errorMsg = "请选择发货人国家/地区";
  }
  return errorMsg ? errorMsg : false;
};

// 校验收货人 有返回错误信息表示校验不通过；返回 false 表示校验通过
export const consigneeInvalida = (state) => {
  let errorMsg = "";
  const {
    consigneeName,
    consigneeAddr,
    consigneeCountryCode,
  } = state.receiveForm;
  if (isEmpty(consigneeName)) {
    errorMsg = "请输入收货人名称";
  } else if (isEmpty(consigneeAddr)) {
    errorMsg = "请输入收货人地址";
  } else if (isEmpty(consigneeCountryCode)) {
    errorMsg = "请选择收货人国家/地区";
  }
  return errorMsg ? errorMsg : false;
};

export const useReceiveForm = ({ state, dicMap, wrapText }) => {
  const { navigateTo } = useTzRouter();

  //收发货人查询
  const consigneeConsigner = (type) => {
    navigateTo({
      path: "/pages/subHK/ccrn/consigneer/index",
      query: {
        type: type,
      },
    });
  };

  return (
    <tz-view class="form-block">
      <tz-text class="form-block-title">收发货人信息</tz-text>
      <tz-form class="receive-form">
        <tz-cell title="发货人名称" border required>
          {wrapText(
            <tz-input
              disabled={state.formsDisabled}
              v-model={state.receiveForm.consignorName}
              type="text"
              placeholder="请输入发货人名称"
              clearable
              maxlength="70"
              rules={(val) => regCommonChar(val)}
            />,
            state.receiveForm.consignorName
          )}

          {!state.formsDisabled && (
            <>
              <tz-icon
                class="tz-input-icon first-icon"
                onClick={() => consigneeConsigner("consigner")}
                name="search"
              ></tz-icon>
              <tz-icon
                class="tz-input-icon"
                name="save"
                onClick={() => saveReceiveMan({ type: "consignor", state })}
              ></tz-icon>
            </>
          )}
        </tz-cell>
        <tz-cell title="发货人地址" border required>
          {wrapText(
            <tz-input
              disabled={state.formsDisabled}
              v-model={state.receiveForm.consignorAddr}
              type="text"
              placeholder="请输入发货人地址"
              clearable
              maxlength="70"
              rules={(val) => regCommonChar(val)}
            />,
            state.receiveForm.consignorAddr
          )}
        </tz-cell>
        <tz-cell title="国家/地区" border required>
          <tz-search-picker
            disabled={state.formsDisabled}
            v-model={state.receiveForm.consignorCountryCode}
            range={dicMap.stateCodeList}
            searchPlaceholder="请输入国家/地区"
            rangeKey="nameLabel"
            valueKey="code"
          ></tz-search-picker>
        </tz-cell>
        <tz-cell title="收货人名称" border required>
          {wrapText(
            <tz-input
              disabled={state.formsDisabled}
              v-model={state.receiveForm.consigneeName}
              type="text"
              placeholder="请输入收货人名称"
              clearable
              maxlength="70"
              rules={(val) => regCommonChar(val)}
            />,
            state.receiveForm.consigneeName
          )}

          {!state.formsDisabled && (
            <>
              <tz-icon
                class="tz-input-icon first-icon"
                onClick={() => consigneeConsigner("consignee")}
                name="search"
              ></tz-icon>
              <tz-icon
                class="tz-input-icon"
                name="save"
                onClick={() => saveReceiveMan({ type: "consignee", state })}
              ></tz-icon>
            </>
          )}
        </tz-cell>
        <tz-cell title="收货人地址" border required>
          {wrapText(
            <tz-input
              disabled={state.formsDisabled}
              v-model={state.receiveForm.consigneeAddr}
              type="text"
              placeholder="请输入收货人地址"
              clearable
              maxlength="70"
              rules={(val) => regCommonChar(val)}
            />,
            state.receiveForm.consigneeAddr
          )}
        </tz-cell>
        <tz-cell title="国家/地区" border required>
          <tz-search-picker
            disabled={state.formsDisabled}
            v-model={state.receiveForm.consigneeCountryCode}
            searchPlaceholder="请输入国家/地区"
            range={dicMap.stateCodeList}
            rangeKey="nameLabel"
            valueKey="code"
          ></tz-search-picker>
        </tz-cell>
      </tz-form>
    </tz-view>
  );
};
